/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import React, { useState, useRef, useCallback, useMemo, useEffect } from 'react';
import './index.less';
import { useInteraction } from '../../utils/useInteraction';
interface ImageViewerProps {
  imgSrcProp: string;
}

const ImageViewer: React.FC<ImageViewerProps> = ({ imgSrcProp }) => {
  const [transformScale, setTransformScale] = useState(1);
  const [transformRotation, setTransformRotation] = useState(0);
  const lastScale = useRef(1);
  const lastRotation = useRef(0);
  // 使用 useRef 存储频繁访问的值
  const stateRef = useRef({
    startDist: 0,
    startAngle: 0,
    lastScale: 1,
    lastRotation: 0
  });

  const imgStyle = useMemo(() => ({
    transform: `scale(${transformScale}) rotate(${transformRotation}deg)`,
    transformOrigin: 'center center'
  }), [transformScale, transformRotation]);

  const getDistance = useCallback((p1, p2) => {
    const dx = p2.globalX - p1.globalX;
    const dy = p2.globalY - p1.globalY;
    return Math.hypot(dx, dy);
  }, []);

  const getAngle = useCallback((p1, p2) => {
    const dx = p2.globalX - p1.globalX;
    const dy = p2.globalY - p1.globalY;
    return Math.atan2(dy, dx) * 180 / Math.PI;
  }, []);

  const rotateStart = useCallback((e: any) => {
    if (e.fingerList.length === 1) {
      return;
    } else if (e.fingerList.length === 2) {
      const newDist = getDistance(e.fingerList[0], e.fingerList[1]);
      const newAngle = getAngle(e.fingerList[0], e.fingerList[1]);
      
      // 更新 stateRef 中的值
      stateRef.current.startDist = newDist;
      stateRef.current.startAngle = newAngle;
      stateRef.current.lastScale = lastScale.current;
      stateRef.current.lastRotation = lastRotation.current;
    }
  }, []);

  useEffect(() => {
    lastScale.current = transformScale;
    lastRotation.current = transformRotation;
  }, [transformScale, transformRotation]);
  
  const rotateMove = useCallback((e: any) => {
    if (e.fingerList.length === 1) {
      return;
    } else if (e.fingerList.length === 2) {
      const newDist = getDistance(e.fingerList[0], e.fingerList[1]);
      let newScale = stateRef.current.lastScale * (newDist / stateRef.current.startDist);
      newScale = Math.max(0.3, Math.min(1.1, newScale));
      
      const newAngle = getAngle(e.fingerList[0], e.fingerList[1]);
      
      const diff = newAngle - stateRef.current.startAngle;
      setTransformScale(newScale);
      setTransformRotation(stateRef.current.lastRotation + diff);
    }
  }, [getDistance, getAngle]);

  const rotateEnd = useCallback((e: any) => {
    return;
  }, []);

  const transformImgRef = useInteraction({
    handlers: {
      onRotateStart: (e: any) => rotateStart(e),
      onRotateMove: (e: any) => rotateMove(e),
      onRotateEnd: (e: any) => rotateEnd(e),
    },
    configs: {
      enableScale: true,
      enableRotate: true,
    },
  });

  return (
    <div ref={transformImgRef as any} className='transformImg-container'>
      <img
        src={imgSrcProp}
        alt='image'
        className='transformImg-content'
        style={imgStyle}
      />
    </div>
  );
};

export default ImageViewer;